package org.ssmd3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.ssmd3.pojo.News;
import org.ssmd3.pojo.NewsType;
import org.ssmd3.service.NewsService;
import org.ssmd3.service.NewsTypeService;
import org.ssmd3.util.PageTool;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/news")

public class NewsController {
    @Resource
    NewsTypeService newsTypeService;
    @Resource
    NewsService newsService;

    @RequestMapping("/save")
    public String save(Model model) {
        List<NewsType> plist = newsTypeService.getAllNewsTypeList();
        model.addAttribute("plist", plist);
        return "/news/save";
    }


    @RequestMapping("/dosave")
    public String doSave(Model model, News news, HttpSession session, @RequestParam(value = "a_newsImg", required = false)
            MultipartFile file) {
        //1.保存图片
        if (file != null) {//保存图片
            String path = session.getServletContext().getRealPath("statics/upload");
            String oldFileName = file.getOriginalFilename();
            int mIndex = oldFileName.lastIndexOf(".");
            String nextName = oldFileName.substring(mIndex + 1);

            System.out.println("后缀名:" + nextName);

            if (nextName.equals("jpg")
                    || nextName.equals("png")
                    || nextName.equals("gif")
                    || nextName.equals("jpeg")
                    ) {


                String fileName = new Date().getTime() + "_" + (int) (Math.random() * 1000000) + "_.jpg";
                File file1 = new File(path, fileName);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                try {
                    file.transferTo(file1);
                    //上传成功
                    news.setNewsImg(fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        //2.新增新闻
        newsService.save(news);


        return "redirect:/news/save";
    }


    @RequestMapping("/list")
    public String list(Model model, News news) {

        int totalRecordCount = newsService.getRecordCount(news);

        PageTool pageTool = new PageTool(totalRecordCount, news.getCurrPageNo(), 2);

        int starNum = pageTool.getStartRow();
        int pageSize = pageTool.getPageSize();
        news.setStarNum(starNum);
        news.setPageSize(pageSize);

        List<News> list = newsService.getNewsListPage(news);
        List<NewsType> plist = newsTypeService.getAllNewsTypeList();
        model.addAttribute("list", list);
        model.addAttribute("plist", plist);
        model.addAttribute("news", news);
        model.addAttribute("pageTool", pageTool);
        model.addAttribute("prePages", pageTool.getPrePages());
        model.addAttribute("nextPages", pageTool.getNextPages());


        return "/news/list";
    }

    @RequestMapping("/dodelete")
    @ResponseBody
    public String doDelete(Model model, int id) {
        try {
            newsService.delete(id);
            return "1";

        } catch (Exception e) {
            return "0";
        }

    }

    @RequestMapping("/dodeleteall")
    @ResponseBody
    public String dodeleteAll(String ids) {
        String[] idsArray = ids.split(",");
        try {
            newsService.deleteAll(idsArray);
            return "1";

        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    @RequestMapping("/update")
    public String update(Model model,Integer id) {

        News news=newsService.getOneNews(id);
        List<NewsType> plist = newsTypeService.getAllNewsTypeList();
        model.addAttribute("plist", plist);
        model.addAttribute("news",news);
        return "/news/update";


    }

    @RequestMapping("/doupdate")
    public String doupdate(Model model, News news, HttpSession session, @RequestParam(value = "a_newsImg", required = false)
            MultipartFile file) {
        //1.保存图片
        if (file != null) {//保存图片
            String path = session.getServletContext().getRealPath("statics/upload");
            String oldFileName = file.getOriginalFilename();
            int mIndex = oldFileName.lastIndexOf(".");
            String nextName = oldFileName.substring(mIndex + 1);

//            System.out.println("后缀名:"+nextName);

            if (nextName.equals("jpg")
                    || nextName.equals("png")
                    || nextName.equals("gif")
                    || nextName.equals("jpeg")
                    ) {


                String fileName = new Date().getTime() + "_" + (int) (Math.random() * 1000000) + "_.jpg";
                File file1 = new File(path, fileName);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                try {
                    file.transferTo(file1);
                    //上传成功
                    news.setNewsImg(fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }


        newsService.update(news);


        return "redirect:/news/list";

    }

    @RequestMapping("/edit")
    @ResponseBody
    public String editNews(String title,Integer id){

        try {
            News news = newsService.getOneNews(id);
            news.setTitle(title);
            newsService.update(news);
            return "1";
        }catch (Exception e){
            e.printStackTrace();

        }
        return "0";
    }
}

